/**
 * Create by ray at 2015年3月23日 下午10:18:15.
 * Ray [email:rayinhangzhou@126.com]
 * ExceptionAdvice.java is for : 
 * TODO	
 *
 * Revision History
 *
 * Date@Programmer:	memo
 * ----------------------------------------------------------------
 * 2015年3月23日@Ray:	initial
 **/

package com.rayinhz.bet.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.rayinhz.bet.CommonUtils;
import com.rayinhz.bet.response.CustomException;
import com.rayinhz.bet.response.DataResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@ControllerAdvice
public class ExceptionAdvice {
	private static Logger	LOG	= LoggerFactory.getLogger(ExceptionAdvice.class);

	@ExceptionHandler(CustomException.class)
	@ResponseBody
	public Object handleRestException(HttpServletRequest request, CustomException ex) {
		String uri = request.getRequestURI();
		String params = JSONObject.toJSONString(request.getParameterMap());
		LOG.error("{}, {}, {}, {}, {}", uri, params, ex.getMsg(), ex.getTag(), CommonUtils.getIp(request), ex.getException());
//		if(uri.contains("/rest/admin/")){
//			Map<String, Object> errorMap = new HashMap<>();
//			errorMap.put("total", 0);
//			errorMap.put("rows", "");
//			errorMap.put("result", restResult.failure(ex.getCode(), ex.getMsg(), ex.getTag()));
//			return errorMap;
//		}
		if(uri.contains(".json") || uri.contains(".jsonp")) {
			return DataResult.fail(ex.getMsg(), ex.getTag());
		} else {
			ModelAndView mav = new ModelAndView();
            mav.addObject("errMsg", ex.getMsg());
            mav.addObject("errResult", ex.getTag());
			mav.setViewName("/exception.jsp");
			return mav;
		}
	}

	@ExceptionHandler(Exception.class)
	@ResponseBody
	public Object handlePageException(HttpServletRequest request, HttpServletResponse response, Exception ex) {
		String uri = request.getRequestURI();
		String params = JSONObject.toJSONString(request.getParameterMap());
		LOG.error("{}, {}, {}", uri, params, CommonUtils.getIp(request), ex);
		response.setStatus(500);
		if(uri.contains(".json") || uri.contains(".jsonp")) {
			return DataResult.fail("system error-->"+ex.getMessage(), ex);
		} else {
			ModelAndView mav = new ModelAndView();
			mav.setViewName("/exception.jsp");
			return mav;
		}
	}
}
